package com.aaron.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.aaron.json.UserBean;

public class Dom4jTest {
	/*
	 * Dom4j操作
	 */
	
	
	//通过url获取远程xml文档并解析
	public Document parseRemote(String url) throws MalformedURLException, DocumentException{
		SAXReader reader = new SAXReader();
		Document dom  = reader.read(new URL(url));
		return dom;
	}
	
	//通过路径读取本地文件并解析
	public Document parseFile(String path) throws FileNotFoundException, DocumentException{
		SAXReader reader = new SAXReader();
		Document dom    = reader.read(new FileInputStream(new File(path)));
		return dom;
	}
	
	//解析XML为Bean数组
	public List<UserBean> resolveBeanList(String path) throws FileNotFoundException, DocumentException{
		
		List<UserBean> beanList  =  new ArrayList<UserBean>();
		
		Document dom   = parseFile(path);
		Element  rootElement = dom.getRootElement();
		Iterator<Element> eleIt = rootElement.elementIterator();
		while(eleIt.hasNext()){
			Element child = eleIt.next();
			String name = child.elementText("name");
			int    id   = Integer.parseInt(child.elementText("id"));
			String p1   = child.elementText("p1");
			String p2   = child.elementText("p2");
			UserBean user = new UserBean(name, id, p1, p2);
			beanList.add(user);
		}
		dom.clearContent();
		return beanList;
	}
	
	
	//Bean数组转换为Document
	public Document convertToDom(List<UserBean> beanList){
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("userList");
		for(UserBean user : beanList){
			Element userElement = root.addElement("user");
			userElement.addElement("name").setText(user.getName());
			userElement.addElement("id").setText(user.getId()+"");
			userElement.addElement("p1").setText(user.getP1());
			userElement.addElement("p2").setText(user.getP2());
		}
		return document;
	}
	
	//将Document写入到文件中
	public void storeFile(Document dom,String path, String encode) throws IOException{
		dom.setXMLEncoding(encode);
		try(FileWriter fileWriter = new FileWriter(path)){
			XMLWriter writer = new XMLWriter(fileWriter);
			writer.write(dom);
			writer.close();
		}
	}
	
	
}
